<template>
  <div class="table-container">
    <!-- <el-button @click="univerData">univer数据</el-button> -->
    <div id="coal-wrapper" class="demo-page-wrapper"></div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: 'DynamicForm',
  inheritAttrs: false,
});

import { CoalDeductionInfo } from '@/utils/formData';
import { integerRule, numberDecimal2, requireRule, validate } from '@/utils/pattern';
import { setupUniver } from '@/utils/setup-univer';
import FormDataAPI from '@/api/batch/formData.api';
import { loadExcelFile, getLetterWordArrFromPosition, calcExcelPosition } from '@/utils/excel';
const props = defineProps<{
  activeTab: string;
  formDataMap: any;
  readonly?: boolean;
  labelMap?: any;
  batchInfo?: any; // 批次信息
}>();
const emit = defineEmits(['update:activeTab']);
const excelData: any = {};
const tableData = ref<CoalDeductionInfo[]>([]);
let univerAPIInstance: any = null; // univer api实例
let univerInstance: any = null; // univer 电子表格实例

const patternMap: any = {
  single_capacity: numberDecimal2,
  declared_val: numberDecimal2,
  capacity_charge: numberDecimal2,
  standard_fall_num: integerRule,
  name: requireRule,
  no: requireRule,
  reason_deduction: requireRule,
};
const getAllValue = async () => {
  const retArr = [];
  for (const key in props.formDataMap) {
    const formData = props.formDataMap[key];
    const item = excelData[formData.formId];
    const fWorkbook = item.workbook;
    let fWorksheet = null;

    const tempInitData = item.tempInitData;
    await fWorkbook.endEditingAsync(true);

    const { formElements = [] } = tempInitData;
    let maxMap: any = {};
    let datasMap: any = {};
    let rows: any = [];
    const sheetData: any = [];
    let sheetDataMap: any = {};
    console.log('formElements-', formElements);
    if (formElements) {
      for (let i = 0; i < formElements.length; i++) {
        const item = formElements[i];
        if (!sheetDataMap[item.sheetName]) {
          sheetDataMap[item.sheetName] = [];
        }
        const arr = item.position.split(',');
        const pos = positionToRange(item.position);
        if (item.sheetId) {
          fWorksheet = fWorkbook.getSheetBySheetId(item.sheetId);
        } else {
          fWorksheet = fWorkbook.getSheets().find((v: any) => v.getIndex() === 0);
        }
        let fRange = fWorksheet.getRange(pos);
        let cdatas = fRange.getCellDatas();
        console.log('cdatas-', cdatas);
        
        datasMap[item.code] = cdatas;
        maxMap[item.code] = (arr[2] - arr[0] + 1) * (arr[3] - arr[1] + 1);
        const cellPositions = item.position.split(',');
        const startPosition = cellPositions[0] + ',' + cellPositions[1];
        cdatas.forEach((row: any, rowIndex: any) => {
          row.forEach((value: any, colIndex: any) => {
            const cuirrentPos = calcExcelPosition(startPosition, {
              row: rowIndex,
              col: colIndex,
            });
            sheetDataMap[item.sheetName].push({
              position: cuirrentPos,
              value: value?.v ?? '',
            });
          });
        });
        sheetDataMap[item.sheetName] = sheetDataMap[item.sheetName].filter((v: any) => {
          return v?.value !== null && v?.value !== undefined && v?.value !== '';
        });
      }
      for (const key in sheetDataMap) {
        sheetData.push({
          sheetName: key,
          celldata: sheetDataMap[key],
        });
      }
      const maxLen = Math.max.apply(Math, Object.values(maxMap));
      // 获取formData i-行数
      for (let i = 0; i < maxLen; i++) {
        rows.push({});
        Object.keys(maxMap).forEach((key) => {
          const value = datasMap[key][i][0]?.v ?? '';
          rows[i][key] = value;
        });
      }
      rows = rows.filter((v: any) => {
        let flag = false;
        for (let key in v) {
          if (v[key]) {
            flag = true;
          }
        }
        return flag;
      });
      console.log('rows-', rows);
    }

    // 获取活动工作簿
    const jsonData = fWorkbook.save();
    console.log('jsonData-', jsonData, sheetData);
    const obj: any = {
      jsonSchema: jsonData,
      formId: formData.formId,
      id: formData.id,
    };
    if (rows) {
      obj.formData = {};
      obj.formData.data = rows;
      obj.formData.sheetData = sheetData;
    }
    retArr.push(obj);
  }

  return retArr;
};

function positionToRange(position: string) {
  const [startRow, startColumn, endRow, endColumn] = position.split(',');
  function getExcelColumn(number: number | string) {
    if (typeof number !== 'number') {
      number = parseInt(number);
    }
    let column = '';
    while (number >= 0) {
      const remainder = number % 26;
      column = String.fromCharCode(remainder + 65) + column;
      number = Math.floor(number / 26) - 1;
      if (number < 0) break;
    }
    return column;
  }
  return `${getExcelColumn(startColumn)}${parseInt(startRow) + 1}:${getExcelColumn(endColumn)}${
    parseInt(endRow) + 1
  }`;
}

async function initWorkbook(item: any) {
  if (univerAPIInstance.getWorkbook(props.labelMap[item.formId])) return;
  const schemaJson: any = item.detail?.schemaJson;
  const tempInitData = JSON.parse(schemaJson || '{}');
  let templateData: any = {}; // 表单数据
  if (!item.id) {
    // 表单定义渲染模板
    templateData = tempInitData?.univerContent;
  } else {
    const formData: any = await FormDataAPI.getFormDataById(item.id);
    let ret = null;
    try {
      const jsonSchema = formData.jsonSchema;
      ret = JSON.parse(jsonSchema);
    } catch {
      ret = {};
    }
    if (JSON.stringify(ret) === '{}') {
      templateData = tempInitData?.univerContent;
    } else {
      templateData = ret;
    }
  }
  templateData.name = props.labelMap[item.formId];
  templateData.id = props.labelMap[item.formId];
  templateData.__formId = item.formId;
  templateData.resources.forEach((v: any) => {
    if (v.name === 'SHEET_RANGE_PROTECTION_PLUGIN') {
      v.data = '';
    }
  });
  console.log('tempInitData-', tempInitData);
  const workbook = univerAPIInstance.createWorkbook(templateData, {
    makeCurrent: false,
  });
  if (tempInitData.permissions && tempInitData.permissions.length !== 0) {
    for (let i = 0; i < workbook.getSheets().length; i++) {
      const sheet = workbook.getSheets()[i];
      const ranges = tempInitData.permissions
        .filter(
          (v: any) => v.sheetId === sheet.getSheetId() || v.sheetName === sheet.getSheetName()
        )
        .map((v: any) => {
          return sheet.getRange(v.meanposition);
        });
      if (ranges.length != 0) {
        const permission = univerAPIInstance.getPermission();
        const { permissionId } = await permission.addRangeBaseProtection(
          workbook.getId(),
          sheet.getSheetId(),
          ranges
        );
        permission.setRangeProtectionPermissionPoint(
          workbook.getId(),
          sheet.getSheetId(),
          permissionId,
          permission.permissionPointsDefinition.RangeProtectionPermissionEditPoint,
          false
        );
      }
    }
  }
  excelData[item.formId] = {
    workbook,
    tempInitData,
  };
  initPermission(workbook);
}
async function initPermission(workbook: any) {
  const permission = univerAPIInstance.getPermission();
  const workBookUnitId = workbook.getId();
  const workbookPermissionArr: any[] = [
    permission.permissionPointsDefinition.WorkbookCreateSheetPermission, // 创建工作簿
    permission.permissionPointsDefinition.WorkbookDeleteSheetPermission, // 删除工作簿
    permission.permissionPointsDefinition.WorkbookRenameSheetPermission, // 重命名工作簿
    permission.permissionPointsDefinition.WorkbookHideSheetPermission, // 隐藏工作簿
    permission.permissionPointsDefinition.WorkbookMoveSheetPermission, // 移动工作簿
  ];

  const worksheetPermissionArr: any[] = [
    permission.permissionPointsDefinition.WorksheetDeleteColumnPermission, // 删除列
    permission.permissionPointsDefinition.WorksheetDeleteRowPermission, // 删除行
    permission.permissionPointsDefinition.WorksheetInsertColumnPermission, // 插入列
    permission.permissionPointsDefinition.WorksheetDeleteRowPermission, // 插入行
    permission.permissionPointsDefinition.WorksheetInsertRowPermission, // 插入行
    permission.permissionPointsDefinition.WorksheetSetCellStylePermission, // 设置单元格样式
    permission.permissionPointsDefinition.WorksheetSetColumnStylePermission, // 设置列样式
    permission.permissionPointsDefinition.WorksheetSetRowStylePermission, // 设置行样式
  ];
  permission.setPermissionDialogVisible(false);
  // unitId 是工作簿的 id, WorkbookEditablePermission 是权限点位, false 表示该权限不可使用
  if (props.readonly) {
    const workbookEditablePermission =
      permission.permissionPointsDefinition.WorkbookEditablePermission;
    permission.setWorkbookPermissionPoint(workBookUnitId, workbookEditablePermission, false);
  }
  workbookPermissionArr.forEach((item) => {
    permission.setWorkbookPermissionPoint(workBookUnitId, item, false);
  });
  // 创建工作表权限，unitId 是工作簿的 id, subUnitId 是工作表的 id，此时生成的权限是一个基础权限，它的作用是用于渲染权限区域
  workbook.getSheets().forEach(async (sheet: any) => {
    const sheetPermission = workbook.getPermission();
    const subUnitId = sheet.getSheetId();
    worksheetPermissionArr.forEach(async (item) => {
      await sheetPermission.setWorksheetPermissionPoint(workBookUnitId, subUnitId, item, false);
    });
  });
}
watch(
  () => props.activeTab,
  async (newVal) => {
    console.log('props.activeTab-', newVal);
    if (newVal) {
      const current = excelData[props.activeTab]?.workbook;
      if (current) {
        univerAPIInstance.setCurrent(current.id);
        const formual = univerAPIInstance.getFormula();
        formual.executeCalculation();
      }
    }
  }
  // { immediate: true }
);
watch(
  () => props.formDataMap,
  async (newVal) => {
    univerAPIInstance.disposeUnit();
    for (const key in newVal) {
      await initWorkbook(newVal[key]);
    }
    const current = excelData[props.activeTab]?.workbook;
    if (!current) return;
    univerAPIInstance.setCurrent(current.id);
    const formual = univerAPIInstance.getFormula();
    formual.executeCalculation();
  },
  {
    deep: true,
  }
);
onMounted(async () => {
  console.log('coal-', props);
  const hiddenMenuArr = [
    'sheet.command.clear-selection-all',
    'sheet.command.clear-selection-format',
    'sheet.command.insert-range-move-right-confirm',
    'sheet.command.insert-range-move-down-confirm',
    'sheet.menu.cell-insert',
    'sheet.menu.delete',
    'sheet.contextMenu.permission',
    'sheet-permission.operation.openPanel',
    'sheet.command.change-sheet-protection-from-sheet-bar',
    'sheet.command.add-range-protection-from-sheet-bar',
    'sheet.command.view-sheet-permission-from-sheet-bar',
    'sheet.command.set-once-format-painter',
    'sheet.command.set-worksheet-show',
    'sheet.mutation.set-worksheet-hidden',
    'sheet.operation.set-worksheet-active',
  ];
  const menu: any = {};
  hiddenMenuArr.forEach((item) => {
    menu[item] = {
      hidden: true,
    };
  });
  const { univerAPI, univer } = setupUniver('coal-wrapper', {
    // data: templateData, // 初始化数据
    header: true,
    footer: true,
    dataValidationConfig: {
      showEditOnDropdown: false,
    },
    menu,
  });
  univerAPIInstance = univerAPI;
  univerInstance = univer;
});
// 销毁
onBeforeUnmount(() => {
  console.log('before-unmount');
  univerInstance?.dispose();
  univerAPIInstance?.dispose();
  univerInstance = null;
  univerAPIInstance = null;
});
defineExpose({
  setValue(value: any) {
    tableData.value = value;
  },
  async getValue() {
    return getAllValue();
  },
  validate: () => validate(tableData.value, patternMap),
  importFile: async (excelFile: File, form: any) => {
    const workbook = await loadExcelFile(excelFile);
    const curExcelData = excelData[form.detail.id];
    const univerWorkbook = curExcelData.workbook;
    const positionArr: any[] = [];
    // 根据定义时候的 formElements 获取 sheet, 坐标等信息
    curExcelData.tempInitData.formElements.forEach((v: any) => {
      const cellPositions = getLetterWordArrFromPosition(v.position);
      cellPositions.forEach((item: any) => {
        if (!positionArr.includes(item)) {
          positionArr.push({
            sheet: univerWorkbook.getSheetBySheetId(v.sheetId),
            sheetName: v.sheetName,
            position: item,
          });
        }
      });
    });
    positionArr.forEach((item: any) => {
      const sheet = workbook.getWorksheet(item.sheetName); // 获取当前sheet
      if (!sheet) return;
      const cell = sheet.getCell(item.position); // 根据坐标获取当前单元格 数据  style等信息
      if (!cell) return;
      const cellValue = cell.value;
      if (!cellValue) return;
      const univerSheet = item.sheet;
      const univerCell = univerSheet.getRange(item.position); // univer sheet 单元格
      if (univerCell.getFormula()) {
        return;
      }
      if (typeof cellValue === 'object') {
        if (cellValue.result) {
          univerCell.setValue(cellValue.result);
        } else if (cellValue.richText) {
          univerCell.setValue(cellValue.richText[0] ? cellValue.richText.reduce((a: any, b: any) => a + b.text, '') : '');
        } else {
          console.error('未识别的数据类型', cellValue);
        }
      } else {
        univerCell.setValue(cellValue);
      }
    });
    univerAPIInstance.setCurrent(univerWorkbook.id);
    const formual = univerAPIInstance.getFormula();
    formual.executeCalculation();
    emit('update:activeTab', form.detail.id);
  },
});
</script>

<style lang="scss" scoped>
.formula-detail {
  display: flex;
  justify-content: flex-end;
}
.formula-collapse {
  max-width: 100%;
  border-radius: 10px;
  background-color: #ffffff;
  padding-left: 10px;

  :deep(.el-collapse-item__header) {
    color: #4080ff;
    background-color: transparent;
  }
}
.formula {
  padding: 5px;
}
.demo-page-wrapper {
  height: 100%;
}
</style>
